const typeModel = require("../../db/models")["type"];
const responseCode = require("../../config/httpCode");
const router = require("koa-router")({
  prefix: "/api/type"
});

router.post("/", async ctx => {
  const { type } = ctx.request.body;
  const has = await typeModel.findOne({
    where: {
      name: type
    }
  });
  if (has) {
    throw responseCode.TAG_EXIST;
  } else {
    const t = await typeModel.create({
      name: type
    });
    ctx.body = {
      code: 200,
      data: t
    };
  }
});

router.get("/", async ctx => {
  const tags = await typeModel.findAll();
  ctx.body = {
    code: 200,
    data: tags
  };
});

router.delete("/:id", async ctx => {
  const id = ctx.params.id;
  await typeModel.destroy({
    where: {
      id
    }
  });
  ctx.body = {
    code: 200
  };
});

module.exports = router;
